﻿@page "/pages/view/{route}"

@inherits BasePagePage
@inject AcBlog.Services.Filters.PageRouteFilter Routes
@inject IPageRenderService PageService
@using AcBlog.Client.UI.Components.Renderers

<Loader OnLoad="@OnLoad" OnLoaded="@OnLoaded" LoadKey="@Route" @ref="loader">
    <ChildContent>
        <PageContainer Title="@Page.Title" PageTitle="@Title">
            <Breadcrumb>
                <Breadcrumb>
                    <BreadcrumbItem>
                        <a href="">
                            <MdiIcon Type="@IconNames.Home" />
                            <span>Home</span>
                        </a>
                    </BreadcrumbItem>
                    <BreadcrumbItem>
                        <span>
                            <MdiIcon Type="@IconNames.Page" />
                            <span>Pages</span>
                        </span>
                    </BreadcrumbItem>
                    <BreadcrumbItem>
                        <span>@Page.Id</span>
                    </BreadcrumbItem>
                </Breadcrumb>
            </Breadcrumb>

            <ChildContent>
                @((MarkupString)Rendered)
            </ChildContent>
        </PageContainer>
    </ChildContent>

    <FailingContent>
        <Result Status="404"
                Title=@("Not Found")
                SubTitle=@("Sorry, the page you visited does not exist.") />
    </FailingContent>
</Loader>

@code {
    [Parameter]
    public string Route { get; set; }

    private Loader loader;

    private Page Page { get; set; }

    private string Rendered { get; set; }

    private Task OnLoaded()
    {
        if (Page is null)
        {
            Title = "Loading...";
        }
        else
        {
            Title = Page.Title;
        }
        return Task.CompletedTask;
    }

    private async Task OnLoad()
    {
        var pages = await Routes.Filter(Route, null);
        var id = pages.Results.First();
        Page = await Service.PageService.Get(id);
        AcBlog.Data.Models.Layout layout = null;
        if (!string.IsNullOrEmpty(Page.Layout))
        {
            try
            {
                layout = await Service.LayoutService.Get(Page.Layout);
            }
            catch
            {
                layout = null;
            }
        }
        Rendered = await PageService.Render(Page, layout);
    }
}
